﻿using HsServerHa.Common.Auth;
using HsServerHa.Entity.Models;
using HsServerHa.Utility.DataHelper;
using HsServerHa.Utility.NetWork;
using HsServerHa.Utility.SQLite;
using Microsoft.Win32;
using Quartz;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Management;
using System.Net.NetworkInformation;
using System.Reflection.Metadata;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace HsServerHa.Jobs
{
    /// <summary>
    /// 该属性告诉Quartz不要同时执行给定Job定义
    /// </summary>
    [DisallowConcurrentExecution]
    public class CheckChildNetworkJob : IJob
    {
        public async Task Execute(IJobExecutionContext context)
        {

            #region 授权验证
            if (!AuthorizationVerification.IsVerification())
            {
                return;
            }
            #endregion
            if (App.isMaster != null)
            {
                //var dataSet = DbHelperSQLite.Query("SELECT * FROM MultipleNetworkCardManage where IsEnable='是'", null);
                //DataTable dt = dataSet.Tables[0];
                //List<MultipleNetworkCardManageEntity> list = DataHelpers.ConvertToModel<MultipleNetworkCardManageEntity>(dt);
                List<MultipleNetworkCardManageEntity> list = await SQLiteHelper.TableAsync<MultipleNetworkCardManageEntity>().Where(x => x.IsEnable == "是").ToListAsync().ConfigureAwait(false);
                if (list == null)
                {
                    return;
                }

                if (App.isMaster.Value)
                {
                    //查询本地网卡信息，并且比对是否加入了虚拟网卡
                    foreach (var item in list)
                    {
                        var isMaster = item.IsMaster;
                        if (isMaster == null)
                        {
                            continue;
                        }
                        if (isMaster == "否")
                        {
                            if (item.IsSyncMAC)
                            {
                                //重置主机mac
                                Task.Run(() =>
                                {
                                    ChangeMacAddress(item.NetworkCardName, item.MAC);
                                });
                            }
                            //DbHelperSQLite.ExecuteSql($"update MultipleNetworkCardManage set IsMaster='是'  where ProgramKey='{item.ProgramKey}'");
                            item.IsMaster = "是";
                            await SQLiteHelper.UpdateAsync(item).ConfigureAwait(false);
                        }
                        if (!NetWorkHelper.IsVirtualIPExists(item.VirtuallyIP) || !NetWorkHelper.IsPingIP(item.VirtuallyIP))
                        {

                            NetWorkHelper.DeleteVirtualIP(item?.VirtuallyIP);
                            int NTEContext = 0;
                            int NTEInstance;
                            string virtualIP = item.VirtuallyIP; // 虚拟IP地址
                            string subnetMask = item.SubnetMask; // 子网掩码
                            int interfaceIndex = NetWorkHelper.GetInterfaceIndex(item.NetworkCardName); // 网卡接口索引
                            if (interfaceIndex == -1)
                            {
                                //AduMessageBoxs.Show("网卡配置错误，请重新选择！");
                                LoggerHelper.Error("网卡配置错误！");
                                return;
                            }

                            var result = NetWorkHelper.AddVirtualIPAddress((uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(virtualIP).GetAddressBytes(), 0), (uint)BitConverter.ToInt32(System.Net.IPAddress.Parse(subnetMask).GetAddressBytes(), 0), interfaceIndex, out NTEContext, out NTEInstance);
                            if (result != 0)
                            {
                                LoggerHelper.Error("切换网卡失败！");
                                //AduMessageBoxs.Show("请检查虚拟IP是否合法！");
                                return;
                            }

                        }


                    }
                }
                else
                {
                    foreach (var item in list)
                    {
                        var isMaster = item.IsMaster;
                        if (isMaster == null)
                        {
                            continue;
                        }
                        if (isMaster == "是")
                        {
                            //DbHelperSQLite.ExecuteSql($"update MultipleNetworkCardManage set IsMaster='否'  where ProgramKey='{item.ProgramKey}'");
                            //重置从机mac
                            if (item.IsSyncMAC)
                            {
                                Task.Run(() =>
                                {
                                    ChangeMacAddress(item.NetworkCardName, item.CurrentMAC);                                   
                                });
                            }


                            item.IsMaster = "否";
                            await SQLiteHelper.UpdateAsync(item).ConfigureAwait(false);
                        }

                        if (NetWorkHelper.IsVirtualIPExists(item.VirtuallyIP))
                        {
                            NetWorkHelper.DeleteVirtualIP(item?.VirtuallyIP);
                            //NetWorkHelper.DeleteIPAddress(item?.VirtuallyIPKey == null ? 0 : int.Parse(item.VirtuallyIPKey));
                        }
                    }
                }
            }
        }



        #region 修改MAC地址新方法
        /// <summary>
        /// 修改指定网卡的MAC地址
        /// </summary>
        /// <param name="networkAdapterName">网卡名称</param>
        /// <param name="newMacAddress">新的MAC地址</param>
        /// <returns>是否修改成功</returns>
        public static bool ChangeMacAddress(string networkAdapterName, string newMacAddress)
        {
            try
            {
                // 获取指定名称的网络适配器
                NetworkInterface adapter = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(a => a.Name == networkAdapterName);
                if (adapter == null)
                {
                    return false;
                }

                // 禁用网络适配器
                DisableNetworkAdapter(adapter);

                // 修改注册表中的MAC地址
                if (!SetMacAddressInRegistry(adapter.Id, newMacAddress))
                {
                    return false;
                }

                // 启用网络适配器
                EnableNetworkAdapter(adapter);

                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 禁用网络适配器
        /// </summary>
        /// <param name="adapter"></param>
        private static void DisableNetworkAdapter(NetworkInterface adapter)
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["NetConnectionId"].ToString() == adapter.Name)
                    {
                        obj.InvokeMethod("Disable", null);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 启用网络适配器
        /// </summary>
        /// <param name="adapter"></param>
        private static void EnableNetworkAdapter(NetworkInterface adapter)
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionId != NULL"))
            {
                foreach (ManagementObject obj in searcher.Get())
                {
                    if (obj["NetConnectionId"].ToString() == adapter.Name)
                    {
                        obj.InvokeMethod("Enable", null);
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 修改注册表中的MAC地址
        /// </summary>
        /// <param name="adapterId"></param>
        /// <param name="newMacAddress"></param>
        /// <returns></returns>
        private static bool SetMacAddressInRegistry(string adapterId, string newMacAddress)
        {
            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Control\Class\{4d36e972-e325-11ce-bfc1-08002be10318}", true))
                {
                    if (key != null)
                    {
                        foreach (string subKeyName in key.GetSubKeyNames())
                        {
                            using (RegistryKey subKey = key.OpenSubKey(subKeyName, true))
                            {
                                if (subKey != null)
                                {
                                    object id = subKey.GetValue("NetCfgInstanceId");
                                    if (id != null && id.ToString() == adapterId)
                                    {
                                        object networkAddress = subKey.GetValue("NetworkAddress");
                                        if (networkAddress != null && networkAddress.ToString().Length > 0)
                                        {
                                            subKey.SetValue("NetworkAddress", newMacAddress, RegistryValueKind.String);
                                        }
                                        else
                                        {
                                            subKey.SetValue("NetworkAddress", newMacAddress, RegistryValueKind.String);
                                        }

                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }

                return false;
            }
            catch
            {
                return false;
            }
        }

        #endregion


        #region 废弃
        private ManagementObject? GetNetAdapter(string name)
        {
            //name = "Intel(R) Wi-Fi 6 AX201 160MHz";
            using (ManagementClass mc = new ManagementClass("Win32_NetworkAdapter"))
            {
                var ns = mc.GetInstances().Cast<ManagementObject>().Where(x => x["NetEnabled"] != null && (bool)x["NetEnabled"] == true).ToList();
                return ns.Where(x => (string)x["Name"] == name).FirstOrDefault();
            }
        }

        /// <summary>
        /// 重置Mac地址
        /// </summary>
        /// <param name="adapterName"></param>
        /// <param name="newMac"></param>
        /// <returns></returns>
        private int ReSetMacAddress(string adapterName, string newMac)
        {
            var networkInterface = NetworkInterface.GetAllNetworkInterfaces().First(x => x.Name == adapterName);
            ManagementObject? mo = GetNetAdapter(networkInterface.Description);
            if (mo == null) return -1;
            uint index = (uint)mo["Index"];
            //newMac = "F4-7B-09-7D-0D-07";
            SetMacAddress(index, newMac);

            try
            {
                mo.InvokeMethod("Disable", null);
                mo.InvokeMethod("Enable", null);
            }
            catch
            {
                return -2;
            }
            return 0;
        }
        /// <summary>
        /// 设置mac地址
        /// </summary>
        /// <param name="index"></param>
        /// <param name="newMac"></param>
        private void SetMacAddress(uint index, string newMac)
        {
            //得到 MAC的注册表键
            RegistryKey? macRegistry = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002bE10318}").
                OpenSubKey(index.ToString().PadLeft(4, '0'), true);
            if (macRegistry == null) return;

            if (string.IsNullOrEmpty(newMac))
            {
                macRegistry.DeleteValue("NetworkAddress");
            }
            else
            {
                macRegistry.SetValue("NetworkAddress", newMac);
            }
        }

        /// <summary>
        /// 获取一个随机Mac地址
        /// </summary>
        /// <returns></returns>
        private string GetRandMac()
        {
            //Random random = new Random();
            //// 生成随机的MAC地址
            //byte[] macAddress = new byte[6];
            //random.NextBytes(macAddress);
            //string randomMAC = string.Join("-", macAddress.Select(b => b.ToString("X2")));
            ////randomMAC = "F4-7B-09-7D-0D-07";
            //return randomMAC;
            var random = new Random();
            var buffer = new byte[6];
            random.NextBytes(buffer);
            buffer[0] &= 0b11111110;
            buffer[0] |= 0b00000010;
            var result = string.Concat(buffer.Select(x => string.Format("{0}-", x.ToString("X2"))).ToArray());
            return result.TrimEnd('-');
        }
        #endregion


    }
}
